package zhihuilan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import zhihuilan.common.utils.ToolsUtils;
import zhihuilan.dto.MyStaffShopGoodsDto;
import zhihuilan.dto.WxMiniPageDto;
import zhihuilan.entity.MyStaff;
import zhihuilan.entity.MyStaffShop;
import zhihuilan.entity.MyStaffShopGoods;
import zhihuilan.entity.MySearch;
import zhihuilan.mapper.MyStaffShopGoodsMapper;
import zhihuilan.mapper.MyStaffShopMapper;
import zhihuilan.params.StaticParam;
import zhihuilan.params.query.MyStaffShopGoodsQueryParam;
import zhihuilan.service.MyStaffService;
import zhihuilan.service.MyStaffShopGoodsService;
import zhihuilan.service.MySearchService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 个人商品数据 服务实现
 *
 * @author ruoyi
 */
@Service
public class MyStaffShopGoodsServiceImpl extends ServiceImpl<MyStaffShopGoodsMapper, MyStaffShopGoods> implements MyStaffShopGoodsService {

    private final static String tbName = "staff_shop_goods";

    @Resource
    private MySearchService mySearchService;

    @Resource
    private MyStaffService myStaffService;

    @Autowired
    private MyStaffShopMapper myStaffShopMapper;

//    @Override
//    public Page<MyStaffShopGoods> selectPageList(MyStaffShopGoodsQueryParam queryParam) {
//        QueryWrapper<MyStaffShopGoods> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("status", 1);
//        if (!ObjectUtils.isEmpty(queryParam)) {
//            if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
//                queryWrapper.eq("staff_id", queryParam.getStaffId());
//            }
//            if (!ObjectUtils.isEmpty(queryParam.getStatus())) {
//                queryWrapper.eq("status", queryParam.getStatus());
//            } else {
//                queryWrapper.eq("status", 1);
//            }
//            if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
//                queryWrapper.eq("staff_id", queryParam.getStaffId());
//            }
//            if (!ObjectUtils.isEmpty(queryParam.getType())) {
//                queryWrapper.eq("type", queryParam.getType());
//            }
//        }
//        queryWrapper.orderByDesc("create_time");
//        long pageNum = 0;
//        long pageSize = 10;
//        if (queryParam.getPage() >= 0L) {
//            pageNum = queryParam.getPage();
//        }
//        if (queryParam.getPageSize() > 0L) {
//            pageSize = queryParam.getPageSize();
//        }
//        Page<MyStaffShopGoods> page = new Page<>(pageNum, pageSize);
//        this.baseMapper.selectPage(page, queryWrapper);
//        return page;
//    }

    @Override
    public WxMiniPageDto<MyStaffShopGoodsDto> selectPageList(MyStaffShopGoodsQueryParam queryParam) {
        QueryWrapper<MyStaffShopGoods> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(queryParam)) {
            if (!ObjectUtils.isEmpty(queryParam.getStatus())) {
                queryWrapper.eq("status", queryParam.getStatus());
            } else {
                queryWrapper.eq("status", 1);
            }
            if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
                queryWrapper.eq("staff_id", queryParam.getStaffId());
            }
            if (!ObjectUtils.isEmpty(queryParam.getType())) {
                queryWrapper.eq("type", queryParam.getType());
            } else if (!ObjectUtils.isEmpty(queryParam.getShopId())) {
                queryWrapper.eq("shopid", queryParam.getShopId());
            } else {
                queryWrapper.eq("shopid", 0);
            }
        }
        queryWrapper.orderByDesc("sort");
        long pageNum = 0;
        long pageSize = 10;
        if (queryParam.getPage() >= 0L) {
            pageNum = queryParam.getPage();
        }
        if (queryParam.getPageSize() > 0L) {
            pageSize = queryParam.getPageSize();
        }
        Page<MyStaffShopGoods> page = new Page<>(pageNum, pageSize);
        this.baseMapper.selectPage(page, queryWrapper);
        WxMiniPageDto<MyStaffShopGoodsDto> result = new WxMiniPageDto(page.getCurrent(), page.getSize());
        BeanUtils.copyProperties(page, result);
        List<MyStaffShopGoodsDto> convertList = page.getRecords().stream().map(po -> {
            MyStaffShopGoodsDto dto = new MyStaffShopGoodsDto();
            BeanUtils.copyProperties(po, dto);
            return dto;
        }).collect(Collectors.toList());
        result.setData(convertList);
        return result;
    }

    @Override
    public List<MyStaffShopGoodsDto> selectPageList(Long pageNum, Long pageSize, Integer shopId) {
        QueryWrapper<MyStaffShopGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        if (!ObjectUtils.isEmpty(shopId)) {
            queryWrapper.eq("shopid", shopId);
        }
        queryWrapper.eq("is_tui", 1);
        queryWrapper.orderByDesc("is_tui");
        if (ObjectUtils.isEmpty(pageNum)) {
            pageNum = 0L;
        }
        if (ObjectUtils.isEmpty(pageSize)) {
            pageSize = 3L;
        }
        Page<MyStaffShopGoods> page = new Page<>(pageNum, pageSize);
        this.baseMapper.selectPage(page, queryWrapper);
        return page.getRecords().stream().map(po -> {
            MyStaffShopGoodsDto dto = new MyStaffShopGoodsDto();
            BeanUtils.copyProperties(po, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public Long selectCount(MyStaffShopGoodsQueryParam queryParam) {
        QueryWrapper<MyStaffShopGoods> queryWrapper = new QueryWrapper<>();

        if (!ObjectUtils.isEmpty(queryParam.getStatus())) {
            queryWrapper.eq("status", queryParam.getStatus());
        } else {
            queryWrapper.eq("status", 1);
        }
        if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
            queryWrapper.eq("staff_id", queryParam.getStaffId());
            queryWrapper.eq("shopid", 0);
        }
        if (!ObjectUtils.isEmpty(queryParam.getType())) {
            queryWrapper.eq("type", queryParam.getType());
        }
        if (!ObjectUtils.isEmpty(queryParam.getShopId())) {
            queryWrapper.eq("shopid", queryParam.getShopId());
        }
        Long count = this.baseMapper.selectCount(queryWrapper);
        return count;
    }


    @Override
    public MyStaffShopGoods selectById(Integer id) {
        if (ObjectUtils.isEmpty(id) || id < 1) {
            return null;
        }
        QueryWrapper<MyStaffShopGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("id", id);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Transactional
    @Override
    public MyStaffShopGoods addEntity(MyStaffShopGoods saveEntity) {
        try {
            if (ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.insert(saveEntity);
            } else {
                return null;
            }
            this.updateMySearchInfo(saveEntity, 1);
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public MyStaffShopGoods updateEntity(MyStaffShopGoods saveEntity) {
        try {
            if (!ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.updateById(saveEntity);
            } else {
                return null;
            }
            this.updateMySearchInfo(saveEntity, 2);
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Override
    public Boolean updateSort(Integer id, Integer sort) {
        MyStaffShopGoods goods = this.selectById(id);
        goods.setSort(sort);
        int count = this.baseMapper.updateById(goods);
        return count > 0 ? true : false;
    }

    @Transactional
    @Override
    public Boolean deleteById(Integer id) {
        try {
            MyStaffShopGoods entity = this.selectById(id);
            if (!ObjectUtils.isEmpty(entity)) {
                this.baseMapper.deleteById(id);
            } else {
                return true;
            }
            Boolean result = this.updateMySearchInfo(entity, 3);
            return result;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Override
    public Boolean deleteByShopId(Integer shopId) {
        QueryWrapper<MyStaffShopGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shopid", shopId);
        int count = this.baseMapper.delete(queryWrapper);
        if (count > 0)
            return true;
        else
            return false;
    }

    /**
     * 新增、更新、删除查询表相关信息；
     *
     * @param entity 要插入的数据实体
     * @param type   操作类型：1、新增；2、更新；3、删除；
     * @return 返回操作成功或者失败！
     * @author chenk
     * @date 2025年3月4日 15:50:33
     */
    private Boolean updateMySearchInfo(MyStaffShopGoods entity, Integer type) {
        if (type.equals(3)) {
            this.mySearchService.deleteByTableAndId(tbName, entity.getId());
            return true;
        }
        MySearch mySearch = new MySearch();
        mySearch.setStaffId(entity.getStaffId());
        mySearch.setName(ToolsUtils.replaceCharToSearch(entity.getName()));
        if (!ObjectUtils.isEmpty(entity.getRemark())) {
            String content = ToolsUtils.replaceCharToSearch(entity.getRemark());
            mySearch.setContent(content);
        }
        if (!ObjectUtils.isEmpty(entity.getImage())) {
            String logo = entity.getImage().split(",")[0];
            mySearch.setLogo(!ObjectUtils.isEmpty(logo) ? logo : "");
        }
        mySearch.setTbName(tbName);
        mySearch.setPid(entity.getId());
        mySearch.setType(1);
        mySearch.setUtype(entity.getType());
        if (entity.getShopid().equals(0)) {
            MyStaff myStaff = myStaffService.selectMyStaffById(entity.getStaffId());
            mySearch.setLng(myStaff.getLng());
            mySearch.setLat(myStaff.getLat());
            mySearch.setLnggd(myStaff.getLnggd());
            mySearch.setLatgd(myStaff.getLatgd());
            mySearch.setRegion(myStaff.getRegion());
            mySearch.setDistrictid(!ObjectUtils.isEmpty(myStaff.getDistrictid()) ? myStaff.getDistrictid() : "");
            mySearch.setDistrictid1(!ObjectUtils.isEmpty(myStaff.getDistrictid1()) ? myStaff.getDistrictid1() : "");
            mySearch.setDistrictid2(!ObjectUtils.isEmpty(myStaff.getDistrictid2()) ? myStaff.getDistrictid2() : "");
            mySearch.setAddress(!ObjectUtils.isEmpty(myStaff.getAddress()) ? myStaff.getAddress() : "");
            mySearch.setAddress1(!ObjectUtils.isEmpty(myStaff.getAddress1()) ? myStaff.getAddress1() : "");
            mySearch.setAddress2(!ObjectUtils.isEmpty(myStaff.getAddress2()) ? myStaff.getAddress2() : "");
        } else {
            MyStaffShop shop = this.myStaffShopMapper.selectById(entity.getShopid());
            mySearch.setLng(shop.getLng());
            mySearch.setLat(shop.getLat());
            mySearch.setLnggd(shop.getLnggd());
            mySearch.setLatgd(shop.getLatgd());
            mySearch.setRegion(shop.getRegion());
            mySearch.setDistrictid(!ObjectUtils.isEmpty(shop.getDistrictid()) ? shop.getDistrictid() : "");
            mySearch.setDistrictid1(!ObjectUtils.isEmpty(shop.getDistrictid1()) ? shop.getDistrictid1() : "");
            mySearch.setDistrictid2(!ObjectUtils.isEmpty(shop.getDistrictid2()) ? shop.getDistrictid2() : "");
            mySearch.setAddress(!ObjectUtils.isEmpty(shop.getAddress()) ? shop.getAddress() : "");
            mySearch.setAddress1(!ObjectUtils.isEmpty(shop.getAddress1()) ? shop.getAddress1() : "");
            mySearch.setAddress2(!ObjectUtils.isEmpty(shop.getAddress2()) ? shop.getAddress2() : "");
        }

        mySearch.setCreateTime(Integer.parseInt(new Date().getTime() / 1000 + ""));
        mySearch.setCreateUser(entity.getCreateUser());
        mySearch.setFid(entity.getShopid());
        if (type.equals(1)) {
            this.mySearchService.addEntity(mySearch);
        }
        if (type.equals(2)) {
            this.mySearchService.updateEntity(mySearch);
        }
        return true;
    }

    @Resource
    MyStaffShopGoodsMapper myStaffShopGoodsMapper;

    @Override
    public List<MyStaffShopGoods> selectList(){
        QueryWrapper<MyStaffShopGoods> queryWrapper = new QueryWrapper();
        queryWrapper.eq("status",1);
        queryWrapper.orderByDesc("id");
       // queryWrapper.last(" limit 1500,500");
        return baseMapper.selectList(queryWrapper);

    }

    @Override
    public WxMiniPageDto<MyStaffShopGoodsDto> selectMyStaffShopGoodsList(MyStaffShopGoodsQueryParam queryParam) {
        MPJLambdaWrapper queryWrapper = new MPJLambdaWrapper<MyStaffShopGoodsDto>().setAlias("a");
        List<MyStaffShopGoodsDto> dtoList = new ArrayList<>();
        if (queryParam.getType() != null && queryParam.getType().equals(0)) {
            queryWrapper.select("a.*", "b.title staff_title", "b.logo staff_logo");
            queryWrapper.rightJoin("my_staff_shop b on a.staff_id=b.id");
            queryWrapper.eq("a.status", 1);
            if (!ObjectUtils.isEmpty(queryParam.getId())) {
                MPJLambdaWrapper queryWrapper1 = new MPJLambdaWrapper<MyStaffShopGoodsDto>().setAlias("a");
                queryWrapper1.select("a.*", "b.title staff_title", "b.logo staff_logo");
                queryWrapper1.rightJoin("my_staff_shop b on a.staff_id=b.id");
                queryWrapper1.eq("a.status", 1);
                queryWrapper1.eq("a.id", queryParam.getId());
                dtoList = baseMapper.selectMaps(queryWrapper1);
                queryWrapper.ne("a.id", queryParam.getId());
            }
            queryWrapper.ge("a.shopid", 1);
            queryWrapper.orderByAsc("rand (" + queryParam.getRand() + ")");
            if (queryParam.getDistrictid() != null && queryParam.getDistrictid() > 100000) {
                queryWrapper.eq("b.districtid", queryParam.getDistrictid());
            } else if (queryParam.getDistrictid() != null && queryParam.getDistrictid() < 100000 && queryParam.getDistrictid() > 1000) {
                queryWrapper.eq("b.districtid1", queryParam.getDistrictid());
            } else if (queryParam.getDistrictid() != null && queryParam.getDistrictid() < 1000 && queryParam.getDistrictid() > 0) {
                queryWrapper.eq("b.districtid2", queryParam.getDistrictid());
            }
        } else {
            queryWrapper.select("a.*", "b.title staff_title", "b.logo staff_logo", "b.headimgurl staff_headimgurl");
            queryWrapper.rightJoin("my_staff b on a.staff_id=b.id");
            queryWrapper.eq("a.status", 1);
            if (!ObjectUtils.isEmpty(queryParam.getId())) {
                MPJLambdaWrapper queryWrapper1 = new MPJLambdaWrapper<MyStaffShopGoodsDto>().setAlias("a");
                queryWrapper1.select("a.*", "b.title staff_title", "b.logo staff_logo", "b.headimgurl staff_headimgurl");
                queryWrapper1.rightJoin("my_staff b on a.staff_id=b.id");
                queryWrapper1.eq("a.status", 1);
                queryWrapper1.eq("a.id", queryParam.getId());
                dtoList = baseMapper.selectMaps(queryWrapper1);
                queryWrapper.ne("a.id", queryParam.getId());
            }
            queryWrapper.eq("a.shopid", 0);
            queryWrapper.orderByAsc("rand (" + queryParam.getRand() + ")");
            if (queryParam.getDistrictid() != null && queryParam.getDistrictid() > 100000) {
                queryWrapper.eq("b.districtid", queryParam.getDistrictid());
            } else if (queryParam.getDistrictid() != null && queryParam.getDistrictid() < 100000 && queryParam.getDistrictid() > 1000) {
                queryWrapper.eq("b.districtid1", queryParam.getDistrictid());
            } else if (queryParam.getDistrictid() != null && queryParam.getDistrictid() < 1000 && queryParam.getDistrictid() > 0) {
                queryWrapper.eq("b.districtid2", queryParam.getDistrictid());
            }
        }
        Page<MyStaffShopGoodsDto> pageDto1 = myStaffShopGoodsMapper.selectMapsPage(new Page<>(queryParam.getPage(), queryParam.getPageSize()), queryWrapper);

        dtoList.addAll(pageDto1.getRecords());
        //   System.out.println(pageDto1.getRecords());
//        List<MyStaffShopGoodsDto>  list =   baseMapper.selectMyStaffShopGoodsList((queryParam.getPage()-1)*queryParam.getPageSize(),queryParam.getPageSize(),queryParam.getDistrictid(),queryParam.getRand());
//        Integer total = baseMapper.selectMyStaffShopGoodsListTotal(queryParam.getDistrictid());
//        Page<MyStaffShopGoods> page = new Page<>(queryParam.getPage(), queryParam.getPageSize());
        WxMiniPageDto<MyStaffShopGoodsDto> pageDto = new WxMiniPageDto(pageDto1.getCurrent(), pageDto1.getSize());
        BeanUtils.copyProperties(pageDto1, pageDto);
        pageDto.setData(dtoList);
        return pageDto;
    }

    @Override
    public List<MyStaffShopGoods> getStaffShopGoodsTuiList(StaticParam staticParam) {
        QueryWrapper<MyStaffShopGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.ne("id", staticParam.getId());
        queryWrapper.eq("staff_id", staticParam.getStaffId());
        if (staticParam.getType().equals(1)) {
            queryWrapper.eq("shopId", 0);
        } else {
            queryWrapper.eq("shopId", staticParam.getShopId());
        }
        queryWrapper.last("limit 6");
        Random random = new Random();
        queryWrapper.orderByAsc("rand(" + random.nextInt(100) + ")");
        return baseMapper.selectList(queryWrapper);
    }
}
